#!/usr/bin/env Rscript

library(tidyverse)

complete <- read_csv2("../app/data/completo.csv", na = "NA",
                      col_types = cols(
                          pais = col_character(),
                          regiao = col_character(),
                          uf = col_character(),
                          mesorregiao = col_character(),
                          microrregiao = col_character(),
                          municipio = col_character(),
                          st_acidente_feriado = col_character(),
                          ds_agente_causador = col_character(),
                          ano_cat = col_integer(),
                          ds_cnae_classe_cat = col_character(),
                          dt_acidente = col_date(),
                          st_dia_semana_acidente = col_character(),
                          ds_emitente_cat = col_character(),
                          hora_acidente = col_time(),
                          idade_cat = col_integer(),
                          cd_indica_obito = col_character(),
                          ds_natureza_lesao = col_character(),
                          ds_cbo = col_character(),
                          ds_parte_corpo_atingida = col_character(),
                          cd_tipo_sexo_empregado_cat = col_character(),
                          ds_tipo_acidente = col_character(),
                          ds_tipo_local_acidente = col_character()
                      ))

#Summarization of the number of accidents occurred by year 2012-2016
mun_by_year <- complete %>%
    group_by(microrregiao, municipio) %>%
    count(ano_cat) %>%
    ungroup() %>%
    select(microrregiao, municipio, ano_cat, n)

micro_by_year  <- complete %>%
    group_by(mesorregiao, microrregiao) %>%
    count(ano_cat) %>%
    ungroup() %>%
    select(mesorregiao, microrregiao, ano_cat, n)

meso_by_year <- complete %>%
    group_by(uf, mesorregiao) %>%
    count(ano_cat) %>%
    ungroup() %>%
    select(uf, mesorregiao, ano_cat, n)

uf_by_year <- complete %>%
    group_by(regiao, uf) %>%
    count(ano_cat) %>%
    ungroup() %>%
    select(regiao, uf, ano_cat, n)

regiao_by_year <- complete %>%
    group_by(pais, regiao) %>%
    count(ano_cat) %>%
    ungroup() %>%
    select(pais, regiao, ano_cat, n)

pais_by_year <- complete %>%
    group_by(pais) %>%
    count(ano_cat) %>%
    ungroup() %>%
    select(pais, ano_cat, n)

write_delim(mun_by_year, "../app/data/radarchart/mun_by_year.csv", delim = ";")
write_delim(micro_by_year, "../app/data/radarchart/micro_by_year.csv", delim = ";")
write_delim(meso_by_year, "../app/data/radarchart/meso_by_year.csv", delim = ";")
write_delim(uf_by_year, "../app/data/radarchart/uf_by_year.csv", delim = ";")
write_delim(regiao_by_year, "../app/data/radarchart/regiao_by_year.csv", delim = ";")
write_delim(pais_by_year, "../app/data/radarchart/pais_by_year.csv", delim = ";")
